package com.xja.security.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * @ClassName MySpringSecurityConfig
 * @Description
 * @Author MaYu
 * @Date 2022/4/12 10:19
 * @Version 1.0
 **/
@Configuration
public class MySpringSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService userDetailsService;

    @Bean
    public PasswordEncoder passwordEncoder(){
        return NoOpPasswordEncoder.getInstance();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        /*auth.inMemoryAuthentication()
                .withUser("admin").password("123456").roles("admin_manager")
                .and()
                .withUser("zhangsan").password("123456").roles("admin_manager", "prod_manager");*/
        auth.userDetailsService(userDetailsService);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.formLogin().loginPage("/login.html").loginProcessingUrl("/myLogin")
                .permitAll().and().csrf().disable();
        http.authorizeRequests()
                .antMatchers("/", "/images/**", "/index.html").permitAll()
                .antMatchers("/prod/**").hasRole("prod_manager")
                .antMatchers("/order/**").hasRole("order_manager")
                .antMatchers("/user/**").hasRole("user_manager")
                .antMatchers("/**").authenticated();

        http.logout().logoutUrl("/myLogout").logoutSuccessUrl("/login.html")
                        .clearAuthentication(true).invalidateHttpSession(true);
        http.exceptionHandling().accessDeniedPage("/403.html");
    }
}
